﻿using System;
using System.Reflection;
using Ue.Eagle.Runtime;
using Ue.Core.FileSystems;

namespace Ue.Eagle.Runtime.FileSystems.Dependencies
{
    public class AssemblyProbingFolder : IAssemblyProbingFolder
    {
        private const string BasePath = "Dependencies";
        private readonly IAppDataFolder appDataFolder;
        private readonly IAssemblyLoader assemblyLoader;

        public AssemblyProbingFolder(
            IAppDataFolder appDataFolder, 
            IAssemblyLoader assemblyLoader)
        {
            this.appDataFolder = appDataFolder;
            this.assemblyLoader = assemblyLoader;
        }

        public bool AssemblyExists(string moduleName)
        {
            return this.appDataFolder.FileExists(this.PrecompiledAssemblyPath(moduleName));
        }

        public DateTime GetAssemblyDateTimeUtc(string moduleName)
        {
            return this.appDataFolder.GetFileLastWriteTimeUtc(this.PrecompiledAssemblyPath(moduleName));
        }

        public string GetAssemblyVirtualPath(string moduleName)
        {
            var path = this.PrecompiledAssemblyPath(moduleName);

            return this.appDataFolder.FileExists(path)
                ? this.appDataFolder.ToToAppPath(path)
                : null;
        }

        public Assembly LoadAssembly(string moduleName)
        {
            var path = this.PrecompiledAssemblyPath(moduleName);

            return this.appDataFolder.FileExists(path)
                ? this.assemblyLoader.Load(moduleName)
                : null;
        }

        public void DeleteAssembly(string moduleName)
        {
            var path = this.PrecompiledAssemblyPath(moduleName);

            this.appDataFolder.Delete(path);
        }

        public void StoreAssembly(string moduleName, string fileName)
        {
            var path = PrecompiledAssemblyPath(moduleName);

            this.appDataFolder.CopyTo(fileName, path);
        }

        private string PrecompiledAssemblyPath(string moduleName) {
            return this.appDataFolder.Combine(BasePath, moduleName + ".dll");
        }
    }
}
